package org.lhr.mina;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

/**
 * refer to http://blog.csdn.net/lxlzhn/article/details/8140146 
 */
public class MinaServer extends IoHandlerAdapter {

	public static void main(String[] args) throws IOException {
		IoAcceptor acceptor = new NioSocketAcceptor();
		
		//不添加则出现错误 则会报错 Don't know how to handle message of type 'java.lang.String'.  Are you missing a protocol encoder?
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
		// 设置服务器端的处理程序
		acceptor.setHandler(new MinaServer());
		acceptor.bind(new InetSocketAddress(60001));
		
		System.out.println("MinaServer started...");
	}

	@Override  
    public void messageReceived(IoSession session, Object message){  
        System.out.println("Request From:" + session.getRemoteAddress() + "  "+ message);  
        session.write("Server Time: "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));  
    }

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		session.write("hello, " + session.getId());
		super.sessionOpened(session);
	}  
	
	
	
}
